<!-- 博客嵌入 pocketbase item -->
<div id="pocketbase">
    <div id="tweetList"></div>
    <a id="moreButton" href="#" onclick="showMore(); return false;">更多</a>
</div>

<script type="text/javascript" src="/js/time-fmt.min.js"></script>

<script type="text/javascript">
    const tweetList = document.getElementById('tweetList');
    const moreButton = document.getElementById('moreButton');
    const apiUrl = "https://note.ftls.xyz/json/pb.json"; //"https://api.ftls.xyz/api/collections/whispers/records";
    let currentPage = 1;

    function escapeHtml(text) {
        const div = document.createElement('div');
        div.textContent = text;
        return div.innerHTML;
    }

    function displayTweets(tweets) {
        tweets.forEach(tweet => {
            const blockquote = document.createElement('blockquote');
            const createdAtDiv = document.createElement('div');
            createdAtDiv.textContent = formatTime(tweet.createdAt); // moment.js 或者 相对时间 Lately.js 也可
            const contentDiv = document.createElement('div');
            contentDiv.innerHTML = escapeHtml(tweet.text).replace(/\!\[.*\]\((.+)\)/g, '<img src="$1" loading="lazy" />');
            blockquote.appendChild(createdAtDiv);
            blockquote.appendChild(contentDiv);
            tweetList.appendChild(blockquote);
        });
        // window.Lately && Lately.init({ target: '.lately' }); // 相对时间 Lately.js 初始化
    }

    function fetchTweets(page) {
        const params = new URLSearchParams({
            sort: '-createdAt',
            perPage: 5,
            page: page
        });
        const url = `${apiUrl}?${params.toString()}`;

        fetch(url)
            .then(response => response.json())
            .then(data => {
                displayTweets(data.items);
                if (data.page < data.totalPages) {
                    moreButton.style.display = 'block';
                    currentPage = data.page + 1;
                } else {
                    moreButton.style.display = 'none';
                }
            });
    }

    function showMore() {
        moreButton.style.display = 'none';
        fetchTweets(currentPage);
    }

    // 页面加载时获取第一页推文
    fetchTweets(currentPage);
</script>
<!-- 简易样式；如果 Hugo 主题有样式可能会被覆盖 -->
<!-- <style>
    blockquote {
        margin: 0;
    }

    blockquote p {
        padding: 15px;
        background: #eee;
        border-radius: 5px;
    }
</style> -->